package com.dict.classes;

import java.sql.*;



import com.mysql.jdbc.PreparedStatement;

public class UserDb {
	String connectionURL = "jdbc:mysql://localhost/dashboard";	
	Connection connection = null;
	Statement statement = null;
	public UserDb() throws Exception {
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		connection = DriverManager.getConnection(connectionURL,"root","111111");
	}
	public void disconnect() throws Exception {
		connection.close();
	}
	public ResultSet loadById(int id) throws Exception {
		ResultSet rs;
		PreparedStatement stmt;
		
		String queryStr = "select * from users where id="+id;
		stmt = (PreparedStatement) connection.prepareStatement(queryStr);
		rs = stmt.executeQuery();
		return rs;
	}
	public int addUser(User user){
		PreparedStatement stmt;
		String queryStr = "INSERT into users (username,password) values (?,?)";
		try
		{
			stmt = (PreparedStatement) connection.prepareStatement(queryStr);
			stmt.setString(1, user.getUsername());
			stmt.setString(2, user.getPassword());
			stmt.executeUpdate();
		}
		catch (SQLException s){
			System.out.println("hata"+s.toString());
		}
		return 1;
	}
	public int updateUser(User user) throws Exception {
		PreparedStatement stmt;
		
		String queryStr = "UPDATE users SET username = ?, password = ? where id= ?";
		stmt = (PreparedStatement) connection.prepareStatement(queryStr);
		stmt.setString(1, user.getUsername());
		stmt.setString(2, user.getPassword());
		stmt.setInt(3, user.getId());
		try
		{
			stmt.executeUpdate();
		} catch (Exception e){
			System.out.println(e.getMessage());
			return 0;
		}
		return 1;
	}
	public boolean deleteUser(int id) throws Exception {
		PreparedStatement stmt;
		
		String queryStr = "DELETE FROM users where id=" + id;
		stmt = (PreparedStatement) connection.prepareStatement(queryStr);
		try {
			stmt.executeUpdate();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return false;
		}
		return true;
	}
	
	public ResultSet authenticateUser(String userName, String password) throws Exception {
		ResultSet rs;
		PreparedStatement stmt;
		String queryStr = "select * from users where username = ? AND password = ?" ;
		stmt = (PreparedStatement) connection.prepareStatement(queryStr);
		stmt.setString(1, userName);
		stmt.setString(2, password);
		rs = stmt.executeQuery();
		return rs;
	}
	
	public ResultSet getAllUsersSet() throws Exception
	{
		ResultSet rs;
		PreparedStatement stmt;		
		String queryStr = "select * from users";
		stmt = (PreparedStatement) connection.prepareStatement(queryStr);
		rs = stmt.executeQuery();
		return rs;
	}

}
